package com.wh.wisdomsite.xbox.client.service.showClient.pr;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.wh.wisdomsite.xbox.al.entity.AlarmSign;
import com.wh.wisdomsite.xbox.al.service.IAlarmSignService;
import com.wh.wisdomsite.xbox.common.Constants;
import com.wh.wisdomsite.xbox.common.annotation.NeedInSessionType;
import com.wh.wisdomsite.xbox.common.annotation.ServiceMethod;
import com.wh.wisdomsite.xbox.common.annotation.ServiceProvider;
import com.wh.wisdomsite.xbox.common.reponse.CommonResult;
import com.wh.wisdomsite.xbox.de.entity.Device;
import com.wh.wisdomsite.xbox.de.service.IDeviceService;
import com.wh.wisdomsite.xbox.pojo.showClient.pr.SclProjectConfigIn;
import com.wh.wisdomsite.xbox.pojo.showClient.pr.SclProjectIn;
import com.wh.wisdomsite.xbox.pr.entity.Project;
import com.wh.wisdomsite.xbox.pr.entity.ProjectConfig;
import com.wh.wisdomsite.xbox.pr.service.IProjectConfigService;
import com.wh.wisdomsite.xbox.pr.service.IProjectService;
import com.wh.wisdomsite.xbox.utils.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 展示端项目 Service
 * @author 丁奕
 * @version V1.0
 * @Package com.wh.wisdomsite.xbox.client.service.showClient.pr
 * @date 2018年12月26日 11:36
 * @Copyright 企业版权所有
 * @Company 贵州万华科技有限公司Copyright (c) 2018
 */
@ServiceProvider()
public class ShowClientProjectService {

    private static final Log logger = LogFactory.getLog(ShowClientProjectService.class);

    @Autowired
    private IProjectService iProjectService;
    
    @Autowired
    private IDeviceService iDeviceService;

    @Autowired
    private IAlarmSignService iAlarmSignService;

    @Autowired
    private IProjectConfigService iProjectConfigService;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    /**
     * 获取项目展示数据
     * @param in
     * @return
     */
    @ServiceMethod(method = "zhgd.showClient.pr.getProjectData", title = "获取项目展示数据", version = "1.0", needInSession = NeedInSessionType.NO)
    public CommonResult getProjectData(SclProjectIn in){
        logger.info("获取项目展示数据->>zhgd.showClient.pr.getProjectList->>开始");
        CommonResult commonResult = new CommonResult();
        //用于返回的项目数据Map
        Map<String,Object> resultData = new HashMap<>();
        try{
            if(StringUtils.isNotEmpty(in.getProjectId())){
                Project project = iProjectService.getById(in.getProjectId());
                if(project != null){
                    //构建项目信息
                    Map<String, Object> projectMap = new HashMap<>();
                    projectMap.put("prId", project.getPrId());
                    projectMap.put("prName", project.getPrName());
                    projectMap.put("prArea", project.getPrArea());
                    projectMap.put("prStart", simpleDateFormat.format(project.getPrStart()));
                    projectMap.put("prEnd", simpleDateFormat.format(project.getPrEnd()));
                    projectMap.put("prLeader", project.getPrLeader());
                    projectMap.put("uoMgr", project.getUnitOperator() != null ? project.getUnitOperator().getUoMgr() : "");
                    projectMap.put("usMgr", project.getUnitSupervisor() != null ? project.getUnitSupervisor().getUsMgr() : "");
                    //合同工期
                    int prContractDuration = (int)((project.getPrEnd().getTime() - project.getPrStart().getTime()) / (1000 * 60 * 60 * 24));
                    if(prContractDuration < 1){
                        prContractDuration = 1;
                    }
                    projectMap.put("prContractDuration", prContractDuration);
                    //剩余时间
                    int prRemainingTime = (int)((project.getPrEnd().getTime() - (new Date()).getTime()) / (1000 * 60 * 60 * 24) > 0 ? (project.getPrEnd().getTime() - (new Date()).getTime()) / (1000 * 60 * 60 * 24) : 0 );
                    projectMap.put("prRemainingTime", prRemainingTime);
                    //工程进度
                    double prProgress = (prContractDuration - prRemainingTime) * 1.0 / prContractDuration * 100;
                    projectMap.put("prProgress", prProgress);
                    projectMap.put("prType", project.getPrTypeName());
                    String prStatus = "";
                    if(project.getPrStart().after(new Date())){
                        prStatus = "未开始";
                    }
                    if(project.getPrStart().before(new Date()) && project.getPrEnd().after(new Date())){
                        prStatus = "在建";
                    }
                    if(project.getPrEnd().before(new Date())){
                        prStatus = "已结束";
                    }
                    projectMap.put("prStatus", prStatus);
                    //向返回结果中存入项目信息
                    resultData.put("project", projectMap);
                    //构建项目的设备信息
                    //设置条件
                    EntityWrapper<Device> ewDevice = new EntityWrapper<>();
                    ewDevice.setEntity(new Device());
                    ewDevice.eq("de.de_prId", in.getProjectId());
                    List<Device> deviceList = iDeviceService.getList(ewDevice);
                    //分类装载设备数据
                    Map<String, Object> deviceMap = loadDeviceData(deviceList);
                    //向返回结果中存入项目设备信息
                    resultData.put("device", deviceMap);
                    //构建项目的报警信息
                    //设置条件
                    EntityWrapper<AlarmSign> ewAlarmSign = new EntityWrapper<AlarmSign>();
                    ewAlarmSign.setEntity(new AlarmSign());
                    ewAlarmSign.eq("a.prId", in.getProjectId());
                    ewAlarmSign.orderBy("a.createDate", false);
                    Page<AlarmSign> page = new Page<>();
                    page.setCurrent(1);
                    page.setSize(10);
                    Page<Map<String, Object>> alarmSignPage = iAlarmSignService.getMapsPage(page, ewAlarmSign);
                    List<Map<String, Object>> alarmList = loadAlarmData(alarmSignPage.getRecords());
                    //向返回结果中存入项目的报警信息
                    resultData.put("alarm", alarmList);
                    commonResult.setCode(Constants.CODE_SUCCESS);
                    commonResult.setMessage(Constants.CODE_SUCCESS_MSG);
                    commonResult.setResult(resultData);
                }else{
                    commonResult.setCode(Constants.CODE_FAIL);
                    commonResult.setMessage(Constants.ZHGH_SHOW_PROJECT_ID_NOT_FIND);
                    commonResult.setResult(resultData);
                }
            }else{
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage(Constants.ZHGH_SHOW_PROJECT_ID_NOT_EMPTY);
                return commonResult;
            }

            logger.info("获取项目展示数据->>zhgd.showClient.pr.getProjectData->>结束");
        }catch (Exception e){
            logger.error("获取项目展示数据->>zhgd.showClient.pr.getProjectData->>异常："+e.getMessage());
            commonResult.setCode(Constants.CODE_FAIL);
            commonResult.setMessage(Constants.CODE_FAIL_MSG);
            in.getXboxRequestContext().setException(new Exception(e.getMessage()));
            e.printStackTrace();
        }
        return commonResult;
    }

    /**
     * 获取/设置项目展示配置数据
     * @param in
     * @return
     */
    @ServiceMethod(method = "zhgd.showClient.pr.getOrSetConfig", title = "获取/设置项目展示配置数据", version = "1.0", needInSession = NeedInSessionType.NO)
    public CommonResult getOrSetConfig(SclProjectConfigIn in){
        logger.info("获取/设置项目展示配置数据->>zhgd.showClient.pr.getOrSetConfig->>开始");
        CommonResult commonResult = new CommonResult();
        //用于返回的项目配置Map
        Map<String, Object> result = new HashMap<>();
        try {
            if(StringUtils.isNotEmpty(in.getProjectId())){
                if(StringUtils.isEmpty(in.getDetailConfig())){
                    //获取项目配置信息
                    EntityWrapper<ProjectConfig> ew = new EntityWrapper<>();
                    ew.setEntity(new ProjectConfig());
                    ew.eq("prId", in.getProjectId());
                    ProjectConfig projectConfig = iProjectConfigService.selectOne(ew);
                    if(projectConfig == null){
                        commonResult.setCode(Constants.CODE_FAIL);
                        commonResult.setMessage(Constants.ZHGH_SHOW_PROJECT_ID_NOT_FIND);
                        return commonResult;
                    }
                    result.put("projectId", projectConfig.getPrId());
                    result.put("detailConfig", projectConfig.getDetailConfig());
                    commonResult.setCode(Constants.CODE_SUCCESS);
                    commonResult.setMessage(Constants.CODE_SUCCESS_MSG);
                    commonResult.setResult(result);
                }else{
                    //设置项目配置信息
                    EntityWrapper<ProjectConfig> ew = new EntityWrapper<>();
                    ew.setEntity(new ProjectConfig());
                    ew.eq("prId", in.getProjectId());
                    ProjectConfig projectConfig = iProjectConfigService.selectOne(ew);
                    if(projectConfig == null){
                        //新建项目配置
                        projectConfig = new ProjectConfig();
                        projectConfig.setPcId(UUID.randomUUID().toString().replace("-",""));
                        projectConfig.setPrId(in.getProjectId());
                        projectConfig.setDetailConfig(in.getDetailConfig());
                        iProjectConfigService.insert(projectConfig);
                        commonResult.setCode(Constants.CODE_SUCCESS);
                        commonResult.setMessage(Constants.CODE_SUCCESS_MSG);
                    }else{
                        //更新项目配置
                        projectConfig.setDetailConfig(in.getDetailConfig());
                        iProjectConfigService.updateById(projectConfig);
                        commonResult.setCode(Constants.CODE_SUCCESS);
                        commonResult.setMessage(Constants.CODE_SUCCESS_MSG);
                    }
                }
            }else{
                commonResult.setCode(Constants.CODE_FAIL);
                commonResult.setMessage(Constants.ZHGH_SHOW_PROJECT_ID_NOT_EMPTY);
                return commonResult;
            }
            logger.info("获取/设置项目展示配置数据->>zhgd.showClient.pr.getOrSetConfig->>结束");

        }catch (Exception e){
            logger.error("获取/设置项目展示配置数据->>zhgd.showClient.pr.getOrSetConfig->>异常："+e.getMessage());
            commonResult.setCode(Constants.CODE_FAIL);
            commonResult.setMessage(Constants.CODE_FAIL_MSG);
            in.getXboxRequestContext().setException(new Exception(e.getMessage()));
            e.printStackTrace();
        }
        return commonResult;
    }

    /**
     * 装载警报数据
     * @param alarmSigns
     * @return
     */
    private List<Map<String,Object>> loadAlarmData(List<Map<String, Object>> alarmSigns) throws Exception{
        List<Map<String,Object>> alarmList = new ArrayList<>();
        //遍历alarmSigns,转换成只有必要字段的Map
        for(Map<String, Object> alarmSignMap : alarmSigns){
            AlarmSign alarmSign = (AlarmSign) ObjectUtils.mapToObject(alarmSignMap, AlarmSign.class);
            Map<String,Object> alarmMap = new HashMap<>();
            alarmMap.put("alarmTime", simpleDateFormat.format(alarmSign.getAlarmTime()));
            alarmMap.put("alarmCategory", alarmSign.getAlarmCategory());
            alarmMap.put("alarmContent", alarmSign.getAlarmContent());
            alarmMap.put("alarmData", alarmSign.getAlarmData()+alarmSign.getMeasureUnit());
            alarmMap.put("alarmStatus", alarmSign.getAlarmStatus());
            alarmList.add(alarmMap);
        }
        return alarmList;
    }

    /**
     * 装载设备数据到deviceMap
     * @return
     */
    private Map<String,Object> loadDeviceData(List<Device> deviceList) {
        //要返回的设备Map
        Map<String, Object> deviceMap = new HashMap<>();
        //视频，扬尘，起重机械的LIST
        List<Map<String, String>> videoList = new ArrayList<>();
        List<Map<String, String>> dustList = new ArrayList<>();
        List<Map<String, String>> craneList = new ArrayList<>();
        //遍历传入的deviceList,分别装入不同的List中
        for(Device device : deviceList){
            Map<String, String> deviceDataMap = new HashMap<>();
            switch (device.getType()){
                case "video":
                    deviceDataMap.put("name", device.getDeName());
                    deviceDataMap.put("url", device.getUrl());
                    videoList.add(deviceDataMap);
                    break;
                case "dust":
                    deviceDataMap.put("name", device.getDeName());
                    deviceDataMap.put("deviceId", device.getDeviceId());
                    dustList.add(deviceDataMap);
                    break;
                case "crane":
                    deviceDataMap.put("name", device.getDeName());
                    deviceDataMap.put("deviceId", device.getDeviceId());
                    craneList.add(deviceDataMap);
                    break;
                default:
                    break;
            }
        }
        deviceMap.put("video", videoList);
        deviceMap.put("dust", dustList);
        deviceMap.put("crane", craneList);
        return deviceMap;
    }
}
